package com.zkthink.ceres.member.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.google.common.collect.Lists;
import com.mysql.cj.util.StringUtils;
import com.zkthink.base.R;
import com.zkthink.base.request.PageParams;
import com.zkthink.base.service.SuperServiceImpl;
import com.zkthink.ceres.common.event.OrderPaidEvent;
import com.zkthink.ceres.member.dao.MemberMapper;
import com.zkthink.ceres.member.dto.MemberAddTagDTO;
import com.zkthink.ceres.member.dto.MemberPageDTO;
import com.zkthink.ceres.member.entity.Member;
import com.zkthink.ceres.member.entity.MemberTagRel;
import com.zkthink.ceres.member.service.MemberService;
import com.zkthink.ceres.member.service.MemberTagRelService;
import com.zkthink.ceres.member.vo.TuiguangVo;
import com.zkthink.context.BaseContextHandler;
import com.zkthink.database.mybatis.conditions.Wraps;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.context.event.EventListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.zkthink.context.BaseContextHandler.getUserId;

/**
 * <p>
 * 业务实现类 商城会员信息
 * </p>
 *
 * @author kellen
 * @date 2020-05-02
 */
@Slf4j
@Service
@AllArgsConstructor
public class MemberServiceImpl extends SuperServiceImpl<MemberMapper, Member> implements
        MemberService {

    private MemberTagRelService tagRelService;

    @Override
    public Member findByOpenid(String openid) {
        return this.getOne(Wraps.<Member>lbQ().eq(Member::getOpenid, openid));
    }

    @Override
    public Member findById(Long id) {
        return baseMapper.selectById(id);
    }

    @Override
    public IPage<Member> page(PageParams<MemberPageDTO> params) {
        return this.baseMapper.page(params.getPage(), params.getModel());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void addTag(MemberAddTagDTO addTagDTO) {
        //删除
        tagRelService.remove(Wraps.<MemberTagRel>lbQ().eq(MemberTagRel::getMid, addTagDTO.getMid()));
        //插入
        List<MemberTagRel> memberTagRels = Lists.newArrayList();
        List<Long> tagIds = addTagDTO.getTagIds();
        tagIds.forEach(e -> {
            MemberTagRel memberTagRel = new MemberTagRel().setTagId(e).setMid(addTagDTO.getMid());
            memberTagRels.add(memberTagRel);
        });
        tagRelService.saveBatch(memberTagRels);
    }

    @Override
    public Member findByAccount(String account) {
        if (StringUtils.isNullOrEmpty(account)) {
            return new Member();
        } else {
            return this.getOne(Wraps.<Member>lbQ().eq(Member::getAccount, account));
        }

    }

    @Override
    public Member findByphone(String phone) {
        return this.getOne(Wraps.<Member>lbQ().eq(Member::getPhone, phone));
    }

    /**
     * 我的推广
     *
     * @return
     */
    @Override
    public Map<String, Object> tuiguang() {
        Map<String, Object> map = new HashMap<>();
        TuiguangVo vo = new TuiguangVo();
        Long mid = getUserId();
        Member member = baseMapper.selectById(mid);
        BeanUtils.copyProperties(member, vo);
        vo.setId(member.getId());
        vo.setTicheng(baseMapper.ticheng(mid));
        map.put("my", vo);
        map.put("tuiguang", baseMapper.tuiguang(member.getPhone()));
        return map;
    }

    /**
     * 推广明细
     *
     * @return
     */
    @Override
    public List<TuiguangVo> tuiguangDetails() {
        Long mid = getUserId();
        return baseMapper.tuiguangDetails(mid);
    }

    @Override
    public Member selectById(Long userId) {
        return baseMapper.selectById(userId);
    }

    @Override
    public List<Member> selectByReferPhone(HashMap<String, Object> referPhoneMap) {
        return baseMapper.selectByMap(referPhoneMap);
    }


    @EventListener
    @Async
    public void handleMemberPay(OrderPaidEvent paidEvent) {
        log.info("开始处理订单支付用户信息更新:{}", paidEvent);
        //查询用户信息
        Member member = this.findById(paidEvent.getMid());
        if (null == member) {
            log.info("用户不存在");
            return;
        }
        //更新用户的消费金额、消费次数、最后消费时间
        member.setLastBuyTime(LocalDateTime.now());
        member.setBuyTimes(member.getBuyTimes() + 1);
        member.setExpendAmount(member.getExpendAmount() + paidEvent.getPaySum());
        this.updateById(member);
    }
}
